<?php

namespace App\Http\Controllers\V1\Informations;

use App\Http\Requests\V1\NoticeProgramRequest;
use App\Models\V1\InfoNoticeProgram;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;
class ProgramsController extends Controller
{
    /**
     * 显示数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.noticeprograms');
    }

    /**
     * 获取数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的数据
        $data = $this->getDataList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条数据显示界面（适用于新增addData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['randomCode'] = 'NPC'.uniqid();
        return view('v1.form.notice_program_item', $data);
    }

    /**
     * 显示数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser['code'];

        return view('v1.form.upload_excel', $data);
    }

    /**
     * 更新数据信息(单元格)
     *
     * @param NoticeProgramRequest $request
     * @return array
     */
    public function updateCellData(NoticeProgramRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '栏目代码[' . $request->input('code') . '],更新失败！',
        ];
        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateProgram($request);

            // 更新信息
            $successFlag = $this->handleUpdate($request, true);
            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '栏目代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新闻栏目[' . $request->input('name') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '栏目代码不能为空';
            $messages['name.required'] = '栏目名称不能为空';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request,$rules,$messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '公告栏目[' . $request->input('name') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除基本信息
     *
     * @param NoticeProgramRequest $request
     * @return array
     */
    public function deleteData(NoticeProgramRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '栏目代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateProgram($request);

            // 删除信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '栏目代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新闻栏目批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 删除信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '新闻栏目批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getDataList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = InfoNoticeProgram::orderBy('updated_at', 'desc')->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = InfoNoticeProgram::where('name', 'like', '%' . $keywords . '%')->orderBy('updated_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新信息验证请求
     *
     * @param NoticeProgramRequest $request
     */
    private function validateProgram(NoticeProgramRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("name") !== null) {
            $rules['name'] = 'bail|required';
        }
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'code' => $request->input('code'),
                'name' => $request->input('name'),
            ];
        }

        $rspObj = InfoNoticeProgram::where('code', $where)->update($updateData);

        return $rspObj;
    }

    /**
     * 处理删除信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = InfoNoticeProgram::where('code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = InfoNoticeProgram::where('code', $where)->delete();
        }

        return $rspObj;
    }

    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
        ];

        $rspObj = InfoNoticeProgram::create($insertData);

        return $rspObj;
    }
}
